package com.seeyon.apps.kk.manager;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.dao.SyncOrgDao;
import com.seeyon.apps.kk.util.RestUtil;
import com.seeyon.apps.kk.util.word.MSWordTool;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.engin.relation.CAP4FormRelationRecordDAO;
import com.seeyon.cap4.form.po.CAPFormRelationRecord;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgLevel;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.DBAgent;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.FileUtil;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.AjaxAccess;
import com.seeyon.ctp.util.json.JSONUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FormDataBaseManagerImpl implements FormDataBaseManager {

	private static final Log log = LogFactory.getLog(FormDataBaseManagerImpl.class);
	
	private SyncOrgDao baseQiangsDao;
	private OrgManager orgManager;
	private FormApi4Cap4 formApi4Cap4;
	private EnumManager enumManagerNew;
	private FreeMarkerConfigurer freemarkerBaseConfig;
	private CAP4FormRelationRecordDAO cap4FormRelationRecordDAO;

	public void setBaseQiangsDao(SyncOrgDao baseQiangsDao) {
		this.baseQiangsDao = baseQiangsDao;
	}

	public void setFreemarkerBaseConfig(FreeMarkerConfigurer freemarkerBaseConfig) {
		this.freemarkerBaseConfig = freemarkerBaseConfig;
	}

	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}

	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}

	public void setCap4FormRelationRecordDAO(
			CAP4FormRelationRecordDAO cap4FormRelationRecordDAO) {
		this.cap4FormRelationRecordDAO = cap4FormRelationRecordDAO;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	@Override
	public Long saveUnflowData(String formCode, String createLoginName, Map<String, Object> params)
			throws BusinessException, SQLException {
		// TODO Auto-generated method stub
		FormBean bean = formApi4Cap4.getFormByFormCode(formCode);
		Map<String, Object> main = new HashMap<String, Object>();
		List<Map<String, Object>> sub = new ArrayList<Map<String,Object>>();
		getFormDataMap(bean, params, main, sub);
		
		FormDataMasterBean dataMasterBean = new FormDataMasterBean(main, bean.getMasterTableBean(), true);
		for(Map<String, Object> map : sub){
			FormTableBean subTable = (FormTableBean) map.get("table");
			Map<String, Object> subAdd = (Map<String, Object>) map.get("data");
			FormDataSubBean formDataSubBean = new FormDataSubBean(subAdd, subTable, dataMasterBean, true);
			dataMasterBean.addSubData(subTable.getTableName(), formDataSubBean);
		}
		V3xOrgMember createUser = orgManager.getMemberByLoginName(createLoginName);
		dataMasterBean.setStartDate(DateUtil.currentDate());
		dataMasterBean.setModifyDate(DateUtil.currentDate());
		dataMasterBean.setApproveDate(DateUtil.currentDate());
		dataMasterBean.setStartMemberId(createUser.getId());
		dataMasterBean.setModifyMemberId(createUser.getId());
		dataMasterBean.setApproveMemberId(createUser.getId());
		formApi4Cap4.saveOrUpdateFormData(dataMasterBean, bean.getId(), true);
		
		CtpContentAll ctpContentAll = new CtpContentAll();
		ctpContentAll.setIdIfNew();
		ctpContentAll.setModuleType(42);
		ctpContentAll.setModuleId(dataMasterBean.getId());
		ctpContentAll.setModuleTemplateId(bean.getId());
		ctpContentAll.setContentType(20);
		ctpContentAll.setContentDataId(dataMasterBean.getId());
		ctpContentAll.setContentTemplateId(bean.getId());
		ctpContentAll.setSort(0);
		ctpContentAll.setCreateId(createUser.getId());
		ctpContentAll.setCreateDate(DateUtil.currentDate());
		ctpContentAll.setModifyId(createUser.getId());
		ctpContentAll.setModifyDate(DateUtil.currentDate());
		DBAgent.save(ctpContentAll);
		return dataMasterBean.getId();
	}

	@Override
	public void deleteUnflowData(String formCode) {
		// TODO Auto-generated method stub
		boolean isLoop = true;
		FlipInfo flipInfo = new FlipInfo(1, 200);
		FormBean formBean;
		try {
			formBean = formApi4Cap4.getFormByFormCode(formCode);
		} catch (BusinessException e1) {
			// TODO Auto-generated catch block
			log.error("##客开日志: 同步前删除底表数据时,获取底表模版异常", e1);
			return ;
		}
		List<FormDataMasterBean> list;
		try {
			list = formApi4Cap4.findMasterDataList(flipInfo , formBean.getId(), null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			list = new ArrayList<FormDataMasterBean>();
			log.error("##客开日志: 同步前删除底表数据时,获取底表数据异常", e);
			return ;
		}
		int error = 0;
		int success = 0;
		while(isLoop){
			//循环获取人员主数据
			if(flipInfo.getPage() != 1){
				try {
					list = formApi4Cap4.findMasterDataList(flipInfo, formBean.getId(), null, null);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					list = new ArrayList<FormDataMasterBean>();
				}
				if(CollectionUtils.isEmpty(list) || list.size() <= 199){
					isLoop = false;
				}
			}
			flipInfo.setPage(flipInfo.getPage() + 1);
			
			for(FormDataMasterBean dataMaster: list){
				try {
					if(formApi4Cap4.deleteFormData(dataMaster.getId(), formBean.getId())){
						CtpContentAll ctpContentAll = new CtpContentAll();
						ctpContentAll.setModuleType(42);
						ctpContentAll.setModuleId(dataMaster.getId());
						ctpContentAll.setModuleTemplateId(formBean.getId());
						ctpContentAll.setContentType(20);
						ctpContentAll.setContentDataId(dataMaster.getId());
						ctpContentAll.setContentTemplateId(formBean.getId());
						DBAgent.delete(ctpContentAll);
						success++;
					} else {
						error++;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					error++;
					log.error("##客开日志: 同步前删除底表数据时,删除底表数据异常", e);
				}
			}
		}
		log.info("##客开日志: ******成功删除底表数据：	"+success+"	条！******");
		log.info("##客开日志: ******删除底表数据失败：	"+error+"	条！******");
	}
	
	@Override
	public String updateFormData(String formCode, FormDataMasterBean dataBean,
			Map<String, Object> params, Map<String, String> unique) throws BusinessException, SQLException {
		// TODO Auto-generated method stub
		String ret = "";
		boolean needUpdate = false;
		FormBean bean = formApi4Cap4.getFormByFormCode(formCode);
		Map<String, Object> main = new HashMap<String, Object>();
		List<Map<String, Object>> sub = new ArrayList<Map<String,Object>>();
		getFormDataMap(bean, params, main, sub);
		//主表字段更新判断
		ret = doUpdateCompare(main, dataBean, null, null, ret);
		if(Strings.isNotEmpty(ret)) {
			ret += " 属性.";
		}
		//从表字段更新判断
		for(Map<String, Object> map: sub){
			FormTableBean subTable = (FormTableBean) map.get("table");
			Map<String, Object> subMap = (Map<String, Object>) map.get("data");
			ret = doUpdateCompare(subMap , dataBean, subTable, unique, ret);
		}
		if(Strings.isNotEmpty(ret)) {
			dataBean.setModifyDate(DateUtil.currentDate());
			formApi4Cap4.saveOrUpdateFormData(dataBean, bean.getId(), true);
		}
		return ret;
	}

	@Override
	public void change2Map(FormFieldBean field, Object obj, Map params){
		String name = field.getName();
		if(obj == null){
			params.put(name, null);
			return ;
		}
		try{
			if(field.getInputType().contains("member")){
				String ids = "";
				for(String uname: obj.toString().split(",")){
					if(NumberUtils.isNumber(uname)){
						if(Strings.isEmpty(ids)){
							ids = uname;
						} else {
							ids += uname;
						}
					} else {
						V3xOrgMember member = baseQiangsDao.getMemberByCode(null, "code", uname);
						if(Strings.isEmpty(ids)){
							ids = member == null ? "" : member.getId().toString();
						} else {
							ids += member == null ? "" : member.getId().toString();
						}
					}
				}
				params.put(name, ids);
			} else if(field.getInputType().contains("department")){
				String ids = "";
				for(String uname: obj.toString().split(",")){
					if(NumberUtils.isNumber(uname)){
						if(Strings.isEmpty(ids)){
							ids = uname;
						} else {
							ids += uname;
						}
					} else {
						V3xOrgDepartment member = baseQiangsDao.getDeptByCode(null, "code", uname);
						if(Strings.isEmpty(ids)){
							ids = member == null ? "" : member.getId().toString();
						} else {
							ids += member == null ? "" : member.getId().toString();
						}
					}
				}
				params.put(name, ids);
			} else if(field.getInputType().contains("post")){
				String ids = "";
				for(String uname: obj.toString().split(",")){
					if(NumberUtils.isNumber(uname)){
						if(Strings.isEmpty(ids)){
							ids = uname;
						} else {
							ids += uname;
						}
					} else {
						V3xOrgPost member = baseQiangsDao.getPostByCode(null, "code", uname);
						if(Strings.isEmpty(ids)){
							ids = member == null ? "" : member.getId().toString();
						} else {
							ids += member == null ? "" : member.getId().toString();
						}
					}
				}
				params.put(name, ids);
			} else if(field.getInputType().contains("level")){
				String ids = "";
				for(String uname: obj.toString().split(",")){
					if(NumberUtils.isNumber(uname)){
						if(Strings.isEmpty(ids)){
							ids = uname;
						} else {
							ids += uname;
						}
					} else {
						V3xOrgLevel member = baseQiangsDao.getLevelByCode(null, "code", uname);
						if(Strings.isEmpty(ids)){
							ids = member == null ? "" : member.getId().toString();
						} else {
							ids += member == null ? "" : member.getId().toString();
						}
					}
				}
				params.put(name, ids);
			} else if(field.getInputType().contains("account")){
				String ids = "";
				for(String aname: obj.toString().split(",")){
					V3xOrgAccount account = orgManager.getAccountByName(aname);
					if(Strings.isEmpty(ids)){
						ids = account.getId().toString();
					} else {
						ids += "," + account.getId().toString();
					}
				}
				params.put(field.getName(), ids);
			} else if(field.getInputType().equals("textarea")){
				params.put(field.getName(), obj.toString());
			} else if(field.getInputType().equals("datetime")
						|| field.getInputType().equals("date")){
				if(obj instanceof Date) {
					params.put(name, obj);
				} else if(obj instanceof String) {
					Date date = null;
					try {
						String[] patterns = new String[] {
								"yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS",
								"yyyy/MM/dd", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss.SSS",
								"MM-dd-yyyy", "MM-dd-yyyy HH:mm", "MM-dd-yyyy HH:mm:ss", "MM-dd-yyyy HH:mm:ss.SSS",
								"MM/dd/yyyy", "MM/dd/yyyy HH:mm", "MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy HH:mm:ss.SSS",
								"yyyy年MM月dd日",
								"MM月dd日yyyy年"};
						date = DateUtils.parseDate(obj.toString(), patterns);
						params.put(name, date);
					} catch (ParseException e) {
						params.put(name, null);
						log.info("##客开日志: 控件名称："+field.getDisplay()+"	类型: "+field.getInputType()+" 数据值：	"+obj.toString()+",不能进行数据转换.");
					}
				} else if(obj instanceof Long){
					Date date = DateUtil.currentDate();
					date.setTime(Long.valueOf(obj.toString()));
					params.put(name, date);
				} else {
					params.put(name, null);
					log.info("##客开日志: 控件名称："+field.getDisplay()+"	类型: "+field.getInputType()+" 数据值：	"+obj.toString()+",不能进行数据转换.");
				}
			} else if(field.getInputType().equals("text")){
				if("VARCHAR".equals(field.getFieldType())){
					params.put(name, obj.toString());
				} else if("DECIMAL".equals(field.getFieldType())){
					if(Strings.isNotEmpty(obj.toString())){
						params.put(name, new BigDecimal(obj.toString()));
					} else {
						params.put(name, null);
					}
				} else {
					params.put(name, obj.toString());
				}
			} else if(field.getInputType().equals("select")
					|| field.getInputType().equals("radio")){
				Long id = field.getEnumId();
				List<CtpEnumItem> list = enumManagerNew.getEmumItemByEmumId(id);
				for(CtpEnumItem item: list){
					if(item.getShowvalue().equals(obj.toString())
							|| item.getId().toString().equals(obj.toString())){
						if("VARCHAR".equals(field.getFieldType())){
							params.put(name, item.getId().toString());
						} else if("DECIMAL".equals(field.getFieldType())){
							params.put(name, new BigDecimal(item.getId()));
						} else {
							params.put(name, obj.toString());
						}
						return;
					}
				}
				params.put(name, null);
				log.info("##客开日志: 控件名称："+field.getDisplay()+"	类型: "+field.getInputType()+" 数据值：	"+obj.toString()+",不能进行数据转换.");
			} else if(field.getInputType().equals("checkbox")){
				if("VARCHAR".equals(field.getFieldType())){
					params.put(name, obj.toString());
				} else if("DECIMAL".equals(field.getFieldType())){
					if(Strings.isNotEmpty(obj.toString())){
						params.put(name, new BigDecimal(obj.toString()));
					} else {
						params.put(name, null);
					}
				} else {
					params.put(name, obj.toString());
				}
			} else if(field.getInputType().equals("number")){
				if(Strings.isNotEmpty(obj.toString())){
					params.put(name, new BigDecimal(obj.toString()));
				} else {
					params.put(name, new BigDecimal(0));
				}
			} else {
				params.put(name, null);
				log.info("##客开日志: 控件名称："+field.getDisplay()+"	类型: "+field.getInputType()+" 数据值：	"+obj.toString()+",不能进行数据转换.");
			}
		} catch(Exception e){
			params.put(name, null);
			log.info("##客开日志: 控件名称："+field.getDisplay()+"	类型: "+field.getInputType()+" 数据值：	"+obj.toString()+",不能进行数据转换.");
			log.error("##客开异常: ", e);
		}
	}

	private void getFormDataMap(FormBean bean, Map<String, Object> params, 
					Map<String, Object> main, List<Map<String, Object>> sub){
		for(String key : params.keySet()){
			FormFieldBean field = bean.getFieldBeanByDisplay(key);
			if(field != null && field.isMasterField()){
				change2Map(field, params.get(key), main);
			} else {
				List<FormTableBean> subTables = bean.getSubTableBean();
				for(FormTableBean subTable: subTables){
					if(key.equals(subTable.getDisplay())){
						List<Map<String, Object>> subData = (List<Map<String, Object>>) params.get(key);
						for(Map<String, Object> map : subData){
							Map<String, Object> subAdd = new HashMap<String, Object>();
							for(String subKey : map.keySet()){
								FormFieldBean subField = bean.getFieldBeanByDisplay(subKey);
								if(subField != null && !subField.isMasterField()){
									change2Map(subField, map.get(subKey), subAdd);
								}
							}
							if(!subAdd.isEmpty()){
								Map<String, Object> listMap = new HashMap<String, Object>();
								listMap.put("table", subTable);
								listMap.put("data", subAdd);
								sub.add(listMap);
							}
						}
						break;
					}
				}
			}
		}
	}
	
	private String doUpdateCompare(Map<String, Object> params, FormDataMasterBean dataBean,
			FormTableBean subTable, Map<String, String> unique, String change){//
		if(subTable == null){
			//主表更新
			for(String key: params.keySet()){
				FormFieldBean field;
				try {
					field = dataBean.getFieldBeanByFieldName(key);
				} catch (BusinessException e) {
					// TODO Auto-generated catch block
					log.info("##客开日志: ", e);
					continue;
				}
				if(field != null && field.isMasterField()){
					if(null == dataBean.getFieldValue(key)){
						if(Strings.isNotEmpty(ParamUtil.getString(params, key))){
							dataBean.addFieldValue(key, params.get(key));
							if(Strings.isBlank(change)){
								change = "修改了表单的" + field.getDisplay();
							} else {
								change += "," + field.getDisplay();
							}
						}
					} else if(!dataBean.getFieldValue(key).equals(params.get(key))){
						dataBean.addFieldValue(key, params.get(key));
						if(Strings.isBlank(change)){
							change = "修改了表单的" + field.getDisplay();
						} else {
							change += "," + field.getDisplay();
						}
					}
				}
			}
		} else {
			//从表更新
			if(unique == null){
				//不存在从表数据唯一校验,直接新增从表行数据
				if(!change.contains("从表 " + subTable.getDisplay()+" 新增了数据记录;")){
					if(Strings.isBlank(change)){
						change = "从表 " + subTable.getDisplay() + " 新增了数据记录;";
					} else {
						change += "; 从表 " + subTable.getDisplay() + " 新增了数据记录;";
					}
				}
				FormDataSubBean formDataSubBean = new FormDataSubBean(params, subTable, dataBean, true);
				dataBean.addSubData(subTable.getTableName(), formDataSubBean);
			} else if(unique.containsKey(subTable.getDisplay())){
				//存在从表数据唯一校验
				String fields = unique.get(subTable.getDisplay()).toString();
				List<FormDataSubBean> subDataList = dataBean.getSubData(subTable .getTableName());
				boolean isUpdate = false;
				for(FormDataSubBean subData: subDataList){
					//判读是同一行的数据
					for(String fieldDisplay: fields.split(",")){
						FormFieldBean field = subTable.getFieldBeanByDisplay(fieldDisplay);
						if(field != null){
							if(subData.getFieldValue(field.getName()) == null){
								if(params.get(field.getName()) == null){
									isUpdate = true;
								} else {
									isUpdate = false;
									break;
								}
							} else if(subData.getFieldValue(field.getName()).equals(params.get(field.getName()))){
								isUpdate = true;
							} else {
								isUpdate = false;
								break;
							}
						}
					}
					if(isUpdate){
						//通过唯一判断该行数据进行更新
						if(!change.contains("从表 " + subTable.getDisplay()+" 修改了数据记录;")){
							if(Strings.isBlank(change)){
								change = "从表 " + subTable.getDisplay() + " 修改了数据记录;";
							} else {
								change += "; 从表 " + subTable.getDisplay() + " 修改了数据记录;";
							}
						}
						for(String key: params.keySet()){
							if(null == subData.getFieldValue(key)){
								if(Strings.isNotEmpty(ParamUtil.getString(params, key))){
									subData.addFieldValue(key, params.get(key));
								}
							} else if(!dataBean.getFieldValue(key).equals(params.get(key))){
								subData.addFieldValue(key, params.get(key));
							}
						}
						break;
					}
				}
				//通过唯一判断该行数据不存在，进行添加
				if(!isUpdate){
					if(!change.contains("从表 " + subTable.getDisplay()+" 新增了数据记录;")){
						if(Strings.isBlank(change)){
							change = "从表 " + subTable.getDisplay() + " 新增了数据记录;";
						} else {
							change += "; 从表 " + subTable.getDisplay() + " 新增了数据记录;";
						}
					}
					FormDataSubBean formDataSubBean = new FormDataSubBean(params, subTable, dataBean, true);
					dataBean.addSubData(subTable.getTableName(), formDataSubBean);
				}
			} else {
				//不存在从表数据唯一校验,直接新增从表行数据
				if(!change.contains("从表 " + subTable.getDisplay()+" 新增了数据记录;")){
					if(Strings.isBlank(change)){
						change = "从表 " + subTable.getDisplay() + " 新增了数据记录;";
					} else {
						change += "; 从表 " + subTable.getDisplay() + " 新增了数据记录;";
					}
				}
				FormDataSubBean formDataSubBean = new FormDataSubBean(params, subTable, dataBean, true);
				dataBean.addSubData(subTable.getTableName(), formDataSubBean);
			}
		}
		return change;
	}
	
	public String updateFormData(String formCode, FormDataMasterBean dataBean, Map<String, Object> param) throws BusinessException, SQLException {
        String ret = null;
        boolean needUpdate = false;
        Set<String> it = param.keySet();
        FormBean bean = formApi4Cap4.getFormByFormCode(formCode);
        for (String key : it) {
            FormFieldBean field = bean.getFieldBeanByDisplay(key);
            if ("VARCHAR".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!ParamUtil.getString(param, key).equals(dataBean.getFieldValue(field.getName()))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else if ("DECIMAL".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getLong(param, key));
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!longToBigDecimal(ParamUtil.getLong(param, key, 0L)).equals(dataBean.getFieldValue(field.getName()))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else if ("TIMESTAMP".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getDate(param, key));
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!dataBean.getFieldValue(field.getName()).equals(ParamUtil.getDate(param, key))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getDate(param, key));
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else if ("DATETIME".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getDate(param, key));
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!dataBean.getFieldValue(field.getName()).equals(ParamUtil.getDate(param, key))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getDate(param, key));
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else if ("TEXTAREA".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!dataBean.getFieldValue(field.getName()).equals(ParamUtil.getString(param, key))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else if ("LONGTEXT".equals(field.getFieldType())) {
                if (null == dataBean.getFieldValue(field.getName())) {
                    if (Strings.isNotEmpty(ParamUtil.getString(param, key))) {
                        needUpdate = true;
                        dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                        log.info("#强生客开，LONGTEXT 数据添加！");
                        if (Strings.isBlank(ret)) {
                            ret = "修改了人员的" + key;
                        } else {
                            ret += "," + key;
                        }
                    }
                } else if (!dataBean.getFieldValue(field.getName()).equals(ParamUtil.getString(param, key))) {
                    needUpdate = true;
                    dataBean.addFieldValue(field.getName(), ParamUtil.getString(param, key));
                    log.info("#强生客开，LONGTEXT 数据修改！");
                    if (Strings.isBlank(ret)) {
                        ret = "修改了人员的" + key;
                    } else {
                        ret += "," + key;
                    }
                }
            } else {
                log.info("##强生客开: 未配置类型: " + field.getFieldType() + " ,不能进行修改日志记录.");
            }
        }
        if (needUpdate) {
            ret += " 属性.";
            dataBean.setModifyDate(DateUtil.currentDate());
            formApi4Cap4.saveOrUpdateFormData(dataBean, bean.getId(), true);
        }
        return ret;
    }
	
    private BigDecimal longToBigDecimal(Long val) {
        return new BigDecimal(val);
    }

    @Override
    public void autoGenerateWord(Long summaryId, FormBean formBean, FormDataMasterBean formDataBean) {
        for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
            //判断控件是否为表单转word控件
            if ("1872888230778916558".equals(fieldBean.getInputType())) {
                Map map = JSONUtil.parseJSONString(fieldBean.getCustomParam(), Map.class);
                if (!map.containsKey("templateId")) {
                    continue;
                }
                map = JSONUtil.parseJSONString(map.get("templateId").toString(), Map.class);
                if (RestUtil.getInstence().authenticate()) {
                    String ret = RestUtil.getInstence().getClient()
                            .get("cap4/wordInjectionCtrl/copyWord?templateId="
                                    + map.get("fileUrl") + "&masterDataId="
                                    + summaryId.toString(), String.class);
                    map = JSONUtil.parseJSONString(ret, Map.class);
                    if ("0".equals(map.get("code").toString())) {
                        map = JSONUtil.parseJSONString(map.get("data").toString(), Map.class);
                        map = JSONUtil.parseJSONString(map.get("attJson").toString(), Map.class);
                        String subReference = map.get("subReference").toString();
                        Long fileId = ParamUtil.getLong(map, "fileUrl", 0L);
                        formDataBean.addFieldValue(fieldBean.getName(), Long.valueOf(subReference));

                        ret = RestUtil.getInstence().getClient()
                                .get("cap4/wordInjectionCtrl/getInjectionData?formId="
                                        + formBean.getId() + "&dataId="
                                        + formDataBean.getId() + "&rightId="
                                        + "&fieldName=" + fieldBean.getName(), String.class);
                        map = JSONUtil.parseJSONString(ret, Map.class);
                        String upTableName = null;
                        if ("0".equals(map.get("code").toString())) {
                            Map<String, String> main = new HashMap<String, String>();
                            List<Map<String, List<Map<String, String>>>> subList = new ArrayList<Map<String, List<Map<String, String>>>>();
                            List<JSONObject> list = JSONUtil.parseJSONString(map.get("data").toString(), List.class);

                            for (JSONObject obj : list) {
                                Map param = JSONUtil.parseJSONString(JSONUtil.toJSONString(obj), Map.class);
                                if (formBean.getFieldBeanByName(ParamUtil.getString(param, "source")).isMasterField()) {
                                    main.put(ParamUtil.getString(param, "target"), ParamUtil.getString(param, "value", ""));
                                } else {
                                    if (subList.size() == 0) {
                                        Map<String, List<Map<String, String>>> table = new HashMap<String, List<Map<String, String>>>();
                                        List<Map<String, String>> rowList = new ArrayList<Map<String, String>>();
                                        table.put(ParamUtil.getString(param, "target"), rowList);
                                        List<Object> columns = JSONUtil.parseJSONString(param.get("value").toString(), List.class);
                                        List<JSONObject> subs = JSONUtil.parseJSONString(param.get("subList").toString(), List.class);
                                        for (int i = 0; i < columns.size(); i++) {
                                            String value = columns.get(i).toString();
                                            Map<String, String> cellMap = JSONUtil.parseJSONString(JSONUtil.toJSONString(subs.get(i)), Map.class);
                                            String key = (ParamUtil.getInt(cellMap, "column").intValue() - 1) + "";
                                            Map<String, String> rowMap = new HashMap<String, String>();
                                            rowMap.put(key, value);
                                            rowList.add(rowMap);
                                        }
                                        subList.add(table);
                                    } else {
                                        String nowTableName = formBean.getFieldBeanByName(ParamUtil.getString(param, "source")).getOwnerTableName();
                                        if (nowTableName.equals(upTableName)) {
                                            Map<String, List<Map<String, String>>> table = subList.get(subList.size() - 1);
                                            List<Map<String, String>> rowList = table.values().iterator().next();
                                            List<Object> columns = JSONUtil.parseJSONString(param.get("value").toString(), List.class);
                                            List<JSONObject> subs = JSONUtil.parseJSONString(param.get("subList").toString(), List.class);
                                            for (int i = 0; i < columns.size(); i++) {
                                                String value = columns.get(i).toString();
                                                Map<String, String> cellMap = JSONUtil.parseJSONString(JSONUtil.toJSONString(subs.get(i)), Map.class);
                                                String key = (ParamUtil.getInt(cellMap, "column").intValue() - 1) + "";

                                                Map<String, String> rowMap = rowList.get(i);
                                                rowMap.put(key, value);
                                            }
                                        } else {
                                            Map<String, List<Map<String, String>>> table = new HashMap<String, List<Map<String, String>>>();
                                            List<Map<String, String>> rowList = new ArrayList<Map<String, String>>();
                                            table.put(ParamUtil.getString(param, "target"), rowList);
                                            List<Object> columns = JSONUtil.parseJSONString(param.get("value").toString(), List.class);
                                            List<JSONObject> subs = JSONUtil.parseJSONString(param.get("subList").toString(), List.class);
                                            for (int i = 0; i < columns.size(); i++) {
                                                String value = columns.get(i).toString();
                                                Map<String, String> cellMap = JSONUtil.parseJSONString(JSONUtil.toJSONString(subs.get(i)), Map.class);
                                                String key = (ParamUtil.getInt(cellMap, "column").intValue() - 1) + "";
                                                Map<String, String> rowMap = new HashMap<String, String>();
                                                rowMap.put(key, value);
                                                rowList.add(rowMap);
                                            }
                                            subList.add(table);
                                        }
                                    }
                                    upTableName = formBean.getFieldBeanByName(ParamUtil.getString(param, "source")).getOwnerTableName();
                                }
                            }
                            try {
                                FileManager fileManager = (FileManager) AppContext.getBean("fileManager");
                                File file = fileManager.getFile(fileId);
                                MSWordTool changer = new MSWordTool();
                                changer.setTemplate(file.getPath());
                                changer.replaceBookMark(main);

                                for (Map<String, List<Map<String, String>>> params : subList) {
                                    String book = params.keySet().iterator().next().toString();
                                    List<Map<String, String>> content = params.get(book);
                                    changer.fillTableAtBookMark(book, content);
                                }
                                File targetFile = new File(file.getPath() + "_new");
                                changer.saveAs(targetFile.getPath());
                                FileUtil.copyFile(targetFile, file);
                                FileUtil.deleteFile(targetFile);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                log.error("##强生客开: ", e);
                            }

                        }
                    }
                }
            }
        }
        try {
            formApi4Cap4.saveOrUpdateFormData(formDataBean, formBean.getId(), true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        }
    }

	
	@Override
	public String fltTemplateIntoString(String key, String templateFileName, Object model) {
		// 保证Configuration能初始化
		String templateString = null;
		try {
			freemarkerBaseConfig.afterPropertiesSet();
			Configuration config = freemarkerBaseConfig.getConfiguration();
			Template template = config.getTemplate(templateFileName);
			templateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
		} catch (IOException e) {
			log.error("Freemark模板"+templateFileName+"获取IOException异常:"  +e.getMessage());
			
		} catch (TemplateException e) {
			log.error("Freemark模板"+templateFileName+"TemplateException异常:" +e.getMessage());
		}
		if(Strings.isEmpty(key)){
			return templateString;
		} else {
			Map params = JSONUtil.parseJSONString(templateString, Map.class);
			if(params.containsKey(key)){
				return ParamUtil.getString(params, key, "");
			} else {
				return "";
			}
		}
	}
	
	@Override
	public List<FormDataMasterBean> findActiveKeyMember(FormBean formBean, FormDataMasterBean formDataMasterBean) throws BusinessException, SQLException {
        // TODO Auto-generated method stub
        List<Long> idList = new ArrayList<Long>();
        FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);

        List<CAPFormRelationRecord> relationList = cap4FormRelationRecordDAO.selectRecordByFormMasterDataId(formDataMasterBean.getId());
        for (FormTableBean subTable : formBean.getTableList()) {
            if (subTable.getDisplay().contains("关键人员简历")) {
                List<FormDataSubBean> formDataSubBean = formDataMasterBean.getSubData(subTable.getTableName());
                for (FormDataSubBean subDataBean : formDataSubBean) {
                    BigDecimal enumId = new BigDecimal(subDataBean.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName()) == null
                    						? "0" : subDataBean.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName()).toString());
                    if(enumId.intValue() == 0){
                    	continue;
                    }
                    String enumvalue = enumManagerNew.getCtpEnumItem(enumId.longValue()).getEnumvalue();
                    if ("2".equals(enumvalue)) {
                        for (CAPFormRelationRecord relation : relationList) {
                            if (subDataBean.getId().equals(relation.getFromSubdataId())) {
                                idList.add(relation.getToMasterDataId());
                            }
                        }
                    }
                }
                break;
            }
        }
        if (CollectionUtils.isNotEmpty(idList)) {
            FlipInfo flip = new FlipInfo(1, 500);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", idList);
            return formApi4Cap4.findMasterDataList(flip, keyBean.getId(), null, map);
        }
        return new ArrayList<FormDataMasterBean>();
    }
	
	@Override
	@AjaxAccess
	public List<Map> getTreeDate(String enumName, String selects, int showLevel) {
		// TODO Auto-generated method stub
		List<Map> mapList = new ArrayList<Map>();
		try{
			CtpEnumBean bean = getCtpEnumBeanByName(enumName);
			if(bean == null) {
				return mapList;
			}
			List<CtpEnumItem> list = enumManagerNew.getEmumItemByEmumId(bean.getId());
			if(0 == showLevel){
				selects = getParentEnum(list, selects);
			} else if(1 == showLevel){//选中顶层
				selects = getChildEnum(list, selects);
			}
			for(CtpEnumItem items : list) {
				if(items.getState() == 0) continue;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", items.getId().toString());
				map.put("name", items.getShowvalue());
				map.put("pid", items.getParentId().toString());
				map.put("checked", false);
				map.put("open", false);
				if(Strings.isNotEmpty(selects)){
					if(selects.contains(ParamUtil.getString(map, "id"))){
						map.put("checked", true);
						map.put("open", true);
					}
				}
				if(items.getParentId().equals(0L)){
					map.put("isTop", true);
				} else {
					map.put("isTop", false);
				}
				if(enumManagerNew.hasEnumChildren(items.getId())){
					map.put("isBotton", true);
				} else {
					List<CtpEnumItem> its = enumManagerNew.getChildEnumItems(items.getId());
					if(CollectionUtils.isEmpty(its)){
						map.put("isBotton", true);
					} else {
						map.put("isBotton", false);
					}
				}
				mapList.add(map);
			}
			return mapList;
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ", e);
		}
		return mapList;
	}
	
	private String getParentEnum(List<CtpEnumItem> list, String ids){
		if(Strings.isNotEmpty(ids)){
			for(CtpEnumItem item : list){
				if(ids.contains(item.getId().toString())
						&& !ids.contains(item.getParentId().toString())){
					ids += "," + item.getParentId().toString();
					ids = getParentEnum(list, ids);
				}
			}
		}
		return ids;
	}
	
	private String getChildEnum(List<CtpEnumItem> list, String ids){
		if(Strings.isNotEmpty(ids)){
			for(CtpEnumItem item : list){
				if(ids.contains(item.getParentId().toString())
						&& !ids.contains(item.getId().toString())
						&& !item.getParentId().equals(0L)){
					ids += "," + item.getId().toString();
					ids = getChildEnum(list, ids);
				}
			}
		}
		return ids;
	}

	private CtpEnumBean getCtpEnumBeanByName(String name){
		try {
			List<CtpEnumBean> item = enumManagerNew.getAllOrgCtpEnum(Constants.DEFAULT_ACCOUNT_ID);
			for(CtpEnumBean bean : item){
				if(name.equals(bean.getEnumname())){
					return bean;
				}
			}
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ", e);
		}
		return null;
	}
}
